import 'dart:io';

import 'package:localstorage/localstorage.dart' as local;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../basic.dart';

class StorageManager {
  /// app全局配置 eg:theme todo late 可考虑使用可空 更安全
  static late SharedPreferences sharedPreferences;

  /// 临时目录(Android 应用内cache、iOS 沙盒)
  static late Directory temporaryDirectory;

  // app_flutter目录 用于缓存用户数据
  static late Directory appDocumentsDirectory;

  ///Android 应用下file
  static late Directory _externalStorageDirectory;

  /// 外部存储目录（临时目录(Android 应用下file 、iOS 沙盒)）
  static Directory get externalStorageDirectory {
    if (Platform.isAndroid) return _externalStorageDirectory;
    return temporaryDirectory;
  }

  /// 初始化必备操作 eg:user数据
  static late local.LocalStorage localStorage;

  static initSP() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  /// 必备数据的初始化操作
  /// 由于是同步操作会导致阻塞,所以应尽量减少存储容量
  static init({String localStorageKey = 'localStorage'}) async {
    // async 异步操作
    // sync 同步操作
    temporaryDirectory = await getTemporaryDirectory();
    appDocumentsDirectory = await getApplicationDocumentsDirectory();
    sharedPreferences = await SharedPreferences.getInstance();
    if (Platform.isAndroid) {
      var externalDir = await getExternalStorageDirectory();
      if (null != externalDir) {
        _externalStorageDirectory = externalDir;
      }
    }
    try {
      await local.initLocalStorage();
      localStorage = local.localStorage;
    } catch (e) {
      LogUtil.e('初始化失败');
    }
  }

  StorageManager._internal();

  static final StorageManager _singleton = StorageManager._internal();

  factory StorageManager() => _singleton;
}
